import urllib.request
from pathlib import Path
import json
import base64

__ocr_url = "http://lingkun.open.woa.com/youtu/ocrapi/advertise_ocr"


def png_to_txt(png_path, txt_path):
    with open(str(png_path), mode="rb") as fs:
        file_content = fs.read()
    body = {
        "session_id": "123",
        "app_id": "123",
        "image": base64.b64encode(file_content).decode("utf-8")
    }
    data = json.dumps(body).encode("utf-8")
    req = urllib.request.Request(url=__ocr_url, data=data, method="POST")
    response = urllib.request.urlopen(req)
    resp_json = response.read().decode("utf-8")
    resp = json.loads(resp_json)
    if resp["errorcode"] != 0:
        return
    text = ''
    items = resp["items"]
    left_space = 500
    line_height = 110
    token_width = 75

    index_y = 0
    multiple_line_item = []
    signal_line_item = []
    items = items[:len(items) - 1]
    for item in items:
        if 'GB/T 2659.2-2022' == item['itemstring']:
            continue
        itemcoord = item['itemcoord']
        y = itemcoord['y']
        if index_y == 0:
            signal_line_item.append(item)
        else:
            if y - index_y > line_height:
                multiple_line_item.append(signal_line_item)
                signal_line_item = []
            signal_line_item.append(item)
        index_y = y

    multiple_line_item.append(signal_line_item)

    for s_line_item in multiple_line_item:
        tmp = sorted(s_line_item, key=lambda x: x['itemcoord']['x'])
        index_x = 0
        for item in tmp:
            itemcoord = item['itemcoord']
            x = itemcoord['x']
            if index_x == 0:
                text += ' ' * int((x - left_space) / token_width)
                text += item['itemstring']
            else:
                text += ' ' * int((x - index_x) / token_width)
                text += item['itemstring']
            index_x = x
        text += '\n'

    print(resp_json)
    print(text)
    with open(txt_path, mode="w") as fs:
        fs.write(text)


if __name__ == '__main__':
    # file_path = '/Users/chenbingkang/Documents/安全二部/金融风控产品中心/码表数据规范需求/GBT2659/image/58.png'
    # txt_path = '/Users/chenbingkang/Documents/安全二部/金融风控产品中心/码表数据规范需求/GBT2659/image/58.txt'
    # png_to_txt(file_path, txt_path)
    image_dir = '/Users/chenbingkang/Documents/安全二部/金融风控产品中心/码表数据规范需求/GBT2659/image'
    txt_path = '/Users/chenbingkang/Documents/安全二部/金融风控产品中心/码表数据规范需求/GBT2659/output.txt'
    path = Path(image_dir)

    for file_path in path.rglob('*.png'):
        png_to_txt(str(file_path), str(file_path) + '.txt')


    def f(x):
        p = str(x)
        p = p.replace('/Users/chenbingkang/Documents/安全二部/金融风控产品中心/码表数据规范需求/GBT2659/image/',
                      '')
        p = p.replace('.png.txt', '')
        return int(p)


    text = ''
    for file_path in sorted(path.rglob('*.txt'), key=lambda x: f(x)):
        with open(str(file_path), mode="r") as fs:
            file_content = fs.read()
            text += file_content
            text += '\n'

    with open(txt_path, mode="w") as fs:
        fs.write(text)
